<template>
	<view class="container">
		<!-- 小程序头部兼容 -->
		<!-- #ifdef MP -->
		<view class="mp-search-box">
			<input class="ser-input" type="text" value="输入关键字搜索" disabled />
		</view>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<u-navbar :custom-back="onNavigationBarButtonTapSelf" :title="title" back-icon-name="map-fill" immersive
			back-icon-color="#333" :background="{background: 'rgba(0,0,0,0)' }" :border-bottom="false">
			<view class="slot-wrap">
				<view class="flex items-center" @tap="onNavigationBarButtonTapSelf()">
					<view class="title-over">{{ schoolInfo.name || '正在获取定位...' }}</view>
					<u-icon size="24" top="2" name="arrow-right"></u-icon>
				</view>
				<view class="mp-search-box" @tap="onNavigationBarSearchInputClickedSelf()">
					<u-icon class="search-icon" color="#606266" top="2" name="search"></u-icon>
					<input class="ser-input" type="text" value="请输入商品 如：汉堡" disabled />
				</view>
			</view>
		</u-navbar>
		<!-- #endif -->
		<!-- 头部轮播 -->
		<view class="carousel-section">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 背景色区域 -->
			<template v-if="carouselList.length == 0">
				<x-skeleton type="banner" :loading="carouselList.length == 0"></x-skeleton>
			</template>
			<template v-else>
				<view class="titleNview-background" :style="{backgroundColor:titleNViewBackground}"></view>
				<u-swiper :list="carouselList" interval="5000" height="350" bg-color="rgba(0,0,0,0)" mode="none"
					@change="swiperChange"></u-swiper>
				<!-- 自定义swiper指示器 -->
				<view class="swiper-dots">
					<text class="num">{{swiperCurrent+1}}</text>
					<text class="sign">/</text>
					<text class="num">{{swiperLength}}</text>
				</view>
			</template>
		</view>
		<!-- 分类 -->
		<template v-if="goodstype.length == 0">
			<x-skeleton type="menu" :loading="goodstype.length == 0" :configs="{gridRows: 1, gridColumns:4}"></x-skeleton>
		</template>
		<template v-else>
			<view class="cate-section">
				<view class="cate-item" v-for="(item,index) in goodstype" :key="index" @click="toListPage(item)">
					<image :src="$ut.setImgae(item.image)"></image>
					<text>{{ item.name }}</text>
				</view>
			</view>
		</template>
		<!-- 加载动画 -->
		<mix-loading v-if="dataLoading" />
		<!-- 推荐商品 -->
		<template v-if="recommendedGoodsData != null">
			<template v-if="recommendedGoodsData.length == 0">
				<x-skeleton type="waterfall" :loading="recommendedGoodsData.length == 0"
					:configs="{gridRows: 1, gridColumns:3}"></x-skeleton>
			</template>
			<template v-else>
				<view class="mx-30 my-32">
					<recommended-goods :list="recommendedGoodsData" :maxLength="goodsDataMaxLength" />
				</view>
			</template>
		</template>
		<!-- 推荐店铺 -->
		<template v-if="recommendedStoresData != null">
			<template v-if="recommendedStoresData.length == 0">
				<x-skeleton type="waterfall" :loading="recommendedStoresData.length == 0"
					:configs="{gridRows: 1, gridColumns:1, headHeight: '260rpx'}"></x-skeleton>
			</template>
			<template v-else>
				<view class="mx-30 my-32">
					<recommended-stores :list="recommendedStoresData"></recommended-stores>
				</view>
			</template>
		</template>
		<template v-if="goodsList.length == 0">
			<x-skeleton type="list" :loading="goodsList.length == 0" :configs="{gridRows: 3}"></x-skeleton>
		</template>
		<template>
			<view class="guess-section">
				<view class="guess-item" v-for="(item, index) in goodsList" :key="index" @click="navToDetailPage(item)">
					<view class="flex">
						<view v-if="item.isOpenSave == 1" class="isBalance-style flex items-center">
							<u-icon name="rmb" color="#f1cf21"></u-icon>
							<text class="ml-8">储值</text>
						</view>
						<view class="image-wrapper">
							<u-image class="recommendImg" v-if="item.isRecommend" width="100" height="100"
								src="/static/images/recommend.png" mode="aspectFill"></u-image>
							<image :src="$ut.setImgae(item.logoImage)" mode="aspectFill"></image>
						</view>
						<view class="content-box">
							<view class="title line-1 font-bold">{{item.name}}</view>
							<view class="evaluation-box mt-8">
								<view class="score">{{ item.score || '暂无评' }}</view>
								<view class="sales">
									<text class="ml-12">销量：{{ item.salesVolume }}</text>
								</view>
							</view>
							<view class="delivery flex items-center justify-between mt-8">
								<view>
									<text>起送 ¥{{ item.startPrice }}</text>
									<text class="ml-8">配送 ¥{{ item.deliveryPrice }}</text>
								</view>
							</view>
							<view class="mt-34 flex items-center">
								<u-tag v-if="item.evaluateTemplate == null" text="暂无评价" size="mini" type="warning"></u-tag>
								<template v-else>
									<template v-for="(items, key) in setTagtoArr(item.evaluateTemplate)">
										<u-tag class="mr-12" :key="key" v-if="key < 3" :text="items" size="mini" type="warning" />
									</template>
								</template>
							</view>
						</view>
					</view>
					<scroll-view class="scroll-view_H" scroll-x>
						<view class="goods-list-box" v-for="(goods, key) in item.recommendShopCommodityList" :key="key"
							@click.stop="$ut.route('pages/store/index',{id: item.id, commodityId: goods.id, commodityTypeId: goods.commodityTypeId})">
							<view class="img-box">
								<view class="recommend font-24">
									招牌
								</view>
								<u-image width="140" height="140" border-radius="12" :src="$ut.setImgae(goods.image)"
									mode="aspectFill"></u-image>
							</view>
							<view class="goods-name line-1 font-26 my-8">{{goods.name}}</view>
							<view class="prices font-28">{{goods.originalPrice}}</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<uni-load-more :status="status"></uni-load-more>
		</template>
	</view>
</template>

<script>
	import recommendedStores from './components/recommended-stores.vue';
	import recommendedGoods from './components/recommended-goods.vue';
	import wxLogin from '@/common/mixins/wxLogin.js';
	import wx from "weixin-js-sdk"; // 微信JS - Sdk
	const jsSdkAPIs = ['getLocation'];
	// #ifdef H5
	import {
		mapState,
		mapMutations
	} from 'vuex';
	// #endif
	export default {
		data() {
			return {
				title: '', //页面标题
				titleNViewBackground: '',
				swiperCurrent: 0,
				swiperLength: 0,
				carouselList: [],
				goodsList: [],
				goodstype: [],
				recommendedGoodsData: [], // 推荐商品列表
				goodsDataMaxLength: 0, // 推荐商品分组后最大数组长度
				recommendedStoresData: [], // 推荐店铺列表
				dataLoading: true, // 加载动画
				schoolInfo: {}, // 当前学校信息
				page: 0,
				loading: false,
				loadMore: true
			};
		},
		components: {
			recommendedStores,
			recommendedGoods
		},
		// 混入微信登录
		// #ifdef H5
		mixins: [wxLogin],
		// #endif
		computed: {
			// #ifdef H5
			...mapState(['hasLogin', 'userInfo']),
			// #endif
			status() {
				if (this.loadMore == false) {
					return "noMore";
				} else if (this.loading) {
					return "loading";
				} else {
					return "more";
				}
			}
		},
		async onLoad() {
			if (this.hasLogin) await this.getUserAddressRecently(); // 公众号获取默认地址
		},
		onReachBottom() {
			this.getShopInfoUserData();
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.page = 0;
			this.goodsList = [];
			this.loading = false;
			this.loadMore = true;
			this.getShopInfoUserData();
		},
		methods: {
			...mapMutations(['updateUserInfo','updateSchoolInfo']),
			// 获取默认定位
			async getUserAddressRecently() {
				// 暂时直接获取第一个学校
				this.$u.api.getComSchool().then(async res => {
					this.schoolInfo = res.dataList[0];
					this.updateSchoolInfo(this.schoolInfo);
					await this.getRecommendShopCommodityUser();
					await this.getRecommendShopInfoUser();
					await this.getShopTypeUserData();
					await this.getComImageData();
					await this.getShopInfoUserData();
					this.dataLoading = false;
				})
				return false;
				if (process.env.NODE_ENV === 'development') {
					this.$u.api.getComSchool().then(res => {
						this.schoolInfo = res.dataList[0];
						this.updateSchoolInfo(this.schoolInfo);
					})
				} else {
					const pageUrl = location.href.split('#')[0];
					this.$u.api.setWxJsSdk({
						thisUrl: pageUrl
					}).then((res) => {
						if (res.code === 200) {
							this.initAPIs(res.data);
						}
					}).catch((err) => {
						console.log(err)
					});
				}

			},
			// jsjdk事件
			initAPIs(param) {
				let that = this;
				wx.config({
					debug: false,
					appId: param.appId,
					timestamp: param.timeStamp,
					nonceStr: param.nonceStr,
					signature: param.signature,
					jsApiList: jsSdkAPIs,
				});

				wx.ready(
					function() {
						wx.checkJsApi({
							jsApiList: jsSdkAPIs,
							success: function(res) {
								wx.getLocation({
									type: 'gcj02',
									success: (res) => {
										console.log(res, '获取到地址定位信息......');
										that.$u.api.getComSchool().then(res => {

										})
										// longitude.value = res.longitude
										// latitude.value = res.latitude
										// console.log('jssdk获取的位置:', res.longitude, res.latitude)
									},
									cancel: (err) => {
										console.error("您已禁止获取位置信息")
									}
								});
							}
						});
					});
				wx.error(function(
					res) {});
			},
			// 标签分解-字符串转数组
			setTagtoArr(str) {
				const arr = str.split(',');
				return arr;
			},
			// 推荐商品
			async getRecommendShopCommodityUser() {
				const data = await this.$u.api.getRecommendShopCommodityUser({schoolId: this.schoolInfo.id});
				if(data.dataList.length == 0) return this.recommendedGoodsData = null;
				let arr = data.dataList;
				// 此处需要进行分组给子组件
				let result = [];
				for (var i = 0; i < arr.length; i += 3) {
					result.push(arr.slice(i, i + 3));
				}
				this.recommendedGoodsData = result;
				// 由于数组从0开始，所以数组长度需要减1才能对应数据
				this.goodsDataMaxLength = result.length - 1;
			},
			async getRecommendShopInfoUser() {
				const data = await this.$u.api.getRecommendShopInfoUser({schoolId: this.schoolInfo.id});
				if(data.dataList.length == 0) return this.recommendedStoresData = null;
				this.recommendedStoresData = data.dataList;
			},
			navToList(item, goods) {
				if (item.isTrade == 0) return this.$u.toast('店铺已打烊');
				this.$ut.route('pages/product/product?id=' + goods.id + "&type=2");
			},
			// 跳转到店铺列表
			toListPage(item) {
				const id = item.id;
				this.$ut.route('pages/store/list', {
					id
				});
			},
			getShopTypeUserData() {
				this.$u.api.getShopTypeUser({}).then(res => {
					this.goodstype = res.dataList;
				})
			},
			getShopInfoUserData() {
				if (this.loading || !this.loadMore) {
					return false;
				} else {
					this.loading = true;
					this.page += 1;
					this.$u.api.getShopInfoUser({
							schoolId: this.schoolInfo.id,
							page: this.page,
							limit: 10,
						}).then(res => {
							const {
								dataList,
								total
							} = res;
							this.goodsList = this.goodsList.concat(dataList);
							if (total <= this.goodsList.length) this.loadMore = false;
							this.loading = false;
						})
						.catch(() => {
							this.loading = false;
							this.page -= 1;
						});
				}
			},
			async getComImageData() {
				this.$u.api.getComImage({}).then(res => {
					res.dataList.forEach(item => {
						item.image = this.$ut.setImgae(item.image);
					})
					this.carouselList = res.dataList;
					// im
					this.titleNViewBackground = this.carouselList[0].color;
					this.swiperLength = this.carouselList.length;
				})
			},
			/**
			 * 请求静态数据只是为了代码不那么乱
			 * 分次请求未作整合
			 */
			async loadData() {
				let carouselList = await this.$api.json('carouselList');
				this.titleNViewBackground = carouselList[0].color;
				this.swiperLength = carouselList.length;
				this.carouselList = carouselList;

				let goodsList = await this.$api.json('goodsList');
				this.goodsList = goodsList || [];
			},
			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e;
				this.swiperCurrent = index;
				this.titleNViewBackground = this.carouselList[index].color;
				this.swiperLength = this.carouselList.length;
			},
			//详情页
			navToDetailPage(item) {
				//this.$ut.route('pages/store/index');
				// //测试数据没有写id，用title代替
				// let id = item.title;
				uni.navigateTo({
					url: `/pages/store/index?id=${item.id}`
				})
			},
			onNavigationBarButtonTapSelf(e) {
				const index = e || 0;
				if (index === 1) {
					this.$ut.route('pages/share/share');
				} else if (index === 0) {
					// #ifdef APP-PLUS
					// 不用管这传，这个是以后做app兼容时才会用到的
					const pages = getCurrentPages();
					const page = pages[pages.length - 1];
					const currentWebview = page.$getAppWebview();
					currentWebview.hideTitleNViewButtonRedDot({
						index
					});
					// #endif
					this.$ut.route('pages/address/selectAddress');
				}
			},
			onNavigationBarSearchInputClickedSelf() {
				this.$ut.route('/pages/product/list');
			},
		},
		// #ifndef MP
		// 标题栏input搜索框点击
		onNavigationBarSearchInputClicked: async function(e) {
			// this.$api.msg('点击了搜索框');
			this.$ut.route('/pages/product/list');
		},
		//点击导航栏 buttons 时触发
		onNavigationBarButtonTap(e) {
			const index = e.index;
			if (index === 1) {
				this.$ut.route('pages/share/share');
			} else if (index === 0) {
				// #ifdef APP-PLUS
				// 不用管这传，这个是以后做app兼容时才会用到的
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const currentWebview = page.$getAppWebview();
				currentWebview.hideTitleNViewButtonRedDot({
					index
				});
				// #endif
				this.$ut.route('pages/address/selectAddress');
			}
		}
		// #endif
	}
</script>

<style lang="scss">
	.slot-wrap {
		display: flex;
		align-items: center;

		/* 如果您想让slot内容占满整个导航栏的宽度 */
		/* flex: 1; */
		/* 如果您想让slot内容与导航栏左右有空隙 */
		/* padding: 0 30rpx; */
		.title-over {
			width: 200rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}

	/* #ifdef H5 */
	.mp-search-box {
		// position: absolute;
		// left: 0;
		// top: 30upx;
		// z-index: 9999;
		width: 500rpx;
		padding: 0 80upx 0 20rpx;
		position: relative;

		.search-icon {
			position: absolute;
			top: 16rpx;
			left: 46rpx;
		}

		.ser-input {
			flex: 1;
			height: 56upx;
			line-height: 56upx;
			text-align: center;
			font-size: 28upx;
			color: $font-color-base;
			border-radius: 20px;
			border: 1rpx solid #d4d4d4;
			background: rgba(213, 213, 213, 0.5);
			padding-left: 68rpx;
			text-align: left;
		}
	}

	// page {
	// 	.cate-section {
	// 		position: relative;
	// 		z-index: 5;
	// 		border-radius: 16upx 16upx 0 0;
	// 		margin-top: -20upx;
	// 	}

	// 	.carousel-section {
	// 		padding: 0;

	// 		.titleNview-placing {
	// 			padding-top: 0;
	// 			height: 0;
	// 		}

	// 		.carousel {
	// 			.carousel-item {
	// 				padding: 0;
	// 			}
	// 		}

	// 		.swiper-dots {
	// 			left: 45upx;
	// 			bottom: 40upx;
	// 		}
	// 	}
	// }

	/* #endif */


	page {
		background: #f5f5f5;
	}

	.m-t {
		margin-top: 16upx;
	}

	/* 头部 轮播图 */
	.carousel-section {
		position: relative;
		padding-top: 10px;

		.titleNview-placing {
			height: var(--status-bar-height);
			padding-top: 44px;
			box-sizing: content-box;
		}

		.titleNview-background {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 426upx;
			transition: .4s;
		}
	}

	.carousel {
		width: 100%;
		height: 350upx;

		.carousel-item {
			width: 100%;
			height: 100%;
			padding: 0 28upx;
			overflow: hidden;
		}

		image {
			width: 100%;
			height: 100%;
			border-radius: 10upx;
		}
	}

	.swiper-dots {
		display: flex;
		position: absolute;
		left: 60upx;
		bottom: 15upx;
		width: 72upx;
		height: 36upx;
		background-image: url();
		background-size: 100% 100%;

		.num {
			width: 36upx;
			height: 36upx;
			border-radius: 50px;
			font-size: 24upx;
			color: #fff;
			text-align: center;
			line-height: 36upx;
		}

		.sign {
			position: absolute;
			top: 0;
			left: 50%;
			line-height: 36upx;
			font-size: 12upx;
			color: #fff;
			transform: translateX(-50%);
		}
	}

	/* 分类 */
	.cate-section {
		display: flex;
		justify-content: space-around;
		align-items: center;
		flex-wrap: wrap;
		padding: 30upx 22upx;

		.cate-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
		}

		/* 原图标颜色太深,不想改图了,所以加了透明度 */
		image {
			width: 88upx;
			height: 88upx;
			margin-bottom: 14upx;
			border-radius: 50%;
			opacity: .7;
			box-shadow: 4upx 4upx 20upx rgba(250, 67, 106, 0.3);
		}
	}

	.ad-1 {
		width: 100%;
		height: 210upx;
		padding: 10upx 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.f-header {
		display: flex;
		align-items: center;
		height: 140upx;
		padding: 6upx 30upx 8upx;
		background-color: #fff;

		image {
			flex-shrink: 0;
			width: 80upx;
			height: 80upx;
			margin-right: 20upx;
		}

		.tit-box {
			flex: 1;
			display: flex;
			flex-direction: column;
		}

		.tit {
			font-size: $font-lg +2upx;
			color: #font-color-dark;
			line-height: 1.3;
		}

		.tit2 {
			font-size: $font-sm;
			color: $font-color-light;
		}

		.icon-you {
			font-size: $font-lg +2upx;
			color: $font-color-light;
		}
	}

	/* 猜你喜欢 */
	.guess-section {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30upx;



		.guess-item {
			// display: flex;
			width: 100%;
			background-color: #fff;
			padding: 24rpx;
			margin-top: 30rpx;
			border-radius: 16rpx;
			position: relative;

			&:nth-child(2n+1) {
				// margin-right: 4%;
			}

			.isBalance-style {
				position: absolute;
				top: 0;
				right: 0;
				border-top-right-radius: 16rpx;
				border-bottom-left-radius: 8rpx;
				background-color: rgb(62, 62, 62);
				color: #f1cf21;
				padding: 4rpx 16rpx;
				font-size: 24rpx;
				font-weight: 200;
			}

			.scroll-view_H {
				white-space: nowrap;
				width: 100%;
			}

			.goods-list-box {
				margin-top: 24rpx;
				margin-right: 32rpx;
				display: inline-block;

				.img-box {
					position: relative;
					overflow: hidden;
					border-radius: 12rpx;

					.recommend {
						position: absolute;
						bottom: 0;
						right: 0;
						background-color: #fd3a4c;
						padding: 2rpx 14rpx;
						z-index: 2;
						color: #fff;
						border-top-left-radius: 12rpx;
					}
				}



				.goods-name {
					width: 140rpx;
				}

				.prices {
					color: #FF0909;
					font-size: 28rpx;
					font-weight: bold;

					&::before {
						content: '￥';
						font-size: 18rpx;
						transform: scale(.5);
					}
				}
			}
		}

		.image-wrapper {
			width: 200rpx;
			height: 200rpx;
			border-radius: 12rpx;
			// overflow: hidden;
			position: relative;

			.recommendImg {
				position: absolute;
				top: -12rpx;
				left: -12rpx;
				z-index: 2;
				width: 100rpx;
				height: 100rpx;
			}

			image {
				width: 100%;
				height: 100%;
				border-radius: 12rpx;
				opacity: 1;
			}
		}

		.content-box {
			margin-left: 24rpx;
			flex: 1;

			.title {
				font-size: 30rpx;
				width: 380rpx;
				color: $font-color-dark;
			}

			.evaluation-box {
				display: flex;
				align-items: flex-end;

				.score {
					color: #e29c51;
					font-size: 28rpx;
					font-weight: bold;

					&::after {
						content: '分';
						font-size: 24rpx;
					}
				}

				.sales {
					font-size: 24rpx;
					color: #999;
				}
			}

			.delivery {
				font-size: 24rpx;
				color: #999;
			}
		}

	}

	::v-deep {
		.u-list-image-wrap {
			padding: 0 30rpx;
		}

		.u-swiper-image {
			border-radius: 16rpx;
		}
	}
</style>